import { makeAutoObservable, runInAction } from "mobx";
import http from '@/request'
import { accountType } from "@/types";
import Taro from "@tarojs/taro";
import categorys from "./categorys";

const localActiveAccount = Taro.getStorageSync('account-info') as accountType
const localActiveIndex = Taro.getStorageSync('account-index') || 0

class Store {
    accountList: accountType[]
    activeAccount?: accountType
    accountIndex: number
    updateActive = (data: accountType | number) => {
        if (typeof data === "number") {
            this.activeAccount = this.accountList[data]
            this.accountIndex = data
        } else {
            this.activeAccount = data
            this.accountIndex = this.accountList.findIndex(item => item.id === data?.id)
        }
        Taro.setStorageSync('account-info', this.activeAccount)
        Taro.setStorageSync('account-index', this.accountIndex)
        categorys.doUpDateCategorys()
    }
    doUpDateAccount = () => {
        http.get('/account/checkActive').then(res => {
            runInAction(() => {
                this.accountList = res.data || [] as accountType[]
                if (this.accountList.length) {
                    const activeAccountIndex = this.accountList.findIndex(item => {
                        return item.id === this.activeAccount?.id
                    })
                    const num = activeAccountIndex > -1 ? activeAccountIndex : 0
                    this.updateActive(num)
                }
            })
        }).catch(err => {
            console.log(err)
        })
    }
  constructor() {
    this.activeAccount = localActiveAccount
    this.accountIndex = localActiveIndex
    makeAutoObservable(this);
  }
}

export default new Store();
